<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Logic\Sms;
use App\Logic\Code;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Models\User;


class WithdrawController extends Controller
{


    /**
     * @OA\Post(
     *     path="/withdraw",
     *     tags={"提现"},
     *     summary="提现",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"amount","code","token"},
     *                 @OA\Property(property="amount", type="number", description="数量"),
     *                 @OA\Property(property="code", type="number", description="验证码"),
     *                 @OA\Property(property="token", type="number", description="币种信息：FIL,RED"),
     *                 @OA\Property(property="withdraw_by", type="number", description="提现类型 address,bank"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function withdraw(Request $request)
    {
        $post_data = $request->all();
        $validateRule = [
            'amount' => 'required',
            'code' => 'required',
            'token' => 'required',
            'withdraw_by' => 'required',
        ];
        $errorMsg = [
            'amount.required' => '请传入提现数量',
            'code.required' => '请传入验证码',
            'token.required' => '请传入币种信息',
            'withdraw_by.required' => '请传入提现类型',
        ];

        $validator = Validator::make($post_data, $validateRule, $errorMsg);
        if ($validator->fails()) {
            $errors = $validator->errors()->all();
            return e_msg(300001, $errors[0]);
        }
        $scene = $request->path();
        $key = $this->user['phone'] . '_code_' . $scene;

        $code_info = Code::code($key, $post_data['code']);
        if ($code_info['status'] === 'ERROR') {
//            return $code_info;
        }
		//if($post_data['token'] == ['FIL']){
        if($post_data['token'] == 'FIL'){
            $coin = 'fil';
            $rel_amount = $this->user['fil'];

            if ($rel_amount < $post_data['amount']) {
                return e_msg(300026, '提现余额不足');
            }
            $brr = [
                'type' => 'fil', //提现币种
            ];

        }else{
            $coin = 'red';

            $rel_amount = $this->user['red'];

            if ($rel_amount < $post_data['amount']) {
                return e_msg(300026, '提现余额不足');
            }
            $brr = [
                'type' => 'red', //提现币种
            ];
            if($post_data['withdraw_by'] == 'address'){
                return e_msg(123456,'分红钱包提现只能提到银行');
            }

        }


        if($post_data['withdraw_by'] == 'address'){
            $address = DB::table("miner_wallet")->where('user_name', $this->user['username'])->where('token', $post_data['token'])->value('address');

            if (!$address) {
                return e_msg(300027, '请先绑定钱包地址');
            }
            $brr['wallet'] = $address;
        }else{

            if(empty($this->user['bank_name']) || empty($this->user['bank_account']) || empty($this->user['bank_legal'])){
                return e_msg(123455,'请填写银行信息');
            }
            $brr['bank_name'] = $this->user['bank_name'];
            $brr['bank_account'] = $this->user['bank_account'];
            $brr['bank_legal'] = $this->user['bank_legal'];
        }

        $withdraw_insert_arr = [
            'type' => $coin,
            'token' => $post_data['token'],
            'amount' => $post_data['amount'],
            'user_name' => $this->user['username'],
            'withdraw_by' => $post_data['withdraw_by'],
        ];


        $fil_insert_arr = [
            'out_account' => $this->user['username'],
            'out_phone' => $this->user['phone'],
            'shift_account' => '自己',
            'shift_phone' => '自己',
            'amount' => -$post_data['amount'],
            'type_note' => '提现',
            'type' => 'withdraw',
            'coin_type' => $coin,
        ];
		
		$userInfo = ['red' => $this->user['red']-$post_data['amount']];//用户减去提现数据
        DB::beginTransaction();

        $rel1 = DB::table('withdraw')->insertGetid($withdraw_insert_arr);
        //$rel2 = DB::table('user')->where('id',$this->user['id'])->decrement('fil',$post_data['amount']);
        if($post_data['token'] == 'FIL') {
            $rel2 = DB::table('user')->where('id',$this->user['id'])->decrement('fil',$post_data['amount']);
        }else{
            $rel2 = DB::table('user') ->where('id',$this->user['id'])->update($userInfo) ;
        }
        $rel3 = DB::table('record_fil')->insertGetid($fil_insert_arr);
        $brr['order_id'] = $rel1;
        $rel4 = Db::table('snapshot')->insert($brr);
       
        if($rel1&&$rel2&&$rel3&&$rel4){
            DB::commit();
            return s_msg('');
        }else{
            DB::rollBack();
            return e_msg(123456,'有问题');
        }

    }






    /**
     * @OA\Post(
     *     path="/admin/withdrawIndex",
     *     tags={"提现"},
     *     summary="记录 ",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"state"},
     *                 @OA\Property(property="state", type="number", description="未审核 1，审核通过1(此字段为2 3为驳回)，不传是所有"),
     *                 @OA\Property(property="key", type="string", description="搜索字段  用户id id, 电话号码 phone，用户名称 username"),
     *                 @OA\Property(property="val", type="string", description="搜索值"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    /**
     * @OA\Post(
     *     path="/withdrawIndex",
     *     tags={"提现"},
     *     summary="记录",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 @OA\Property(property="type", type="number", description="fil,red"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function index(Request $request)
    {
        $post_data = $request->all();
        $where = [];
        if($request->has('limit')){
            $limit = $request->input('limit');
        }else{
            $limit = 15;
        }

        if($request->has('state')){
            $state = $request->input('state');
            if($state === 0){
                $where[] = ['w.state','=',$state];
            }else{
                $where[] = ['w.state','>',0];
            }
        }
        if($request->has('type')){
            $type = $request->input('type');
            $where[] = ['ss.type','=',$type];
            $where[] = ['w.type','=',$type];
        }


        if( isset($post_data['key']) && isset($post_data['val']) ){
            $key = 'u.'.$post_data['key'];
            $where[] = [$key,'=',$post_data['val']];
        }

        if(isset($this->user['id'])){
            $where[] = ['u.username','=',$this->user['username']];
        }
//        dd($where);
        $withdraw_list = DB::table('withdraw as w')
            ->join('user as u','u.username','=','w.user_name')
            ->leftJoin('snapshot as ss','ss.order_id','=','w.id')
            ->where($where)
            ->select('w.*','ss.wallet','ss.bank_name','ss.bank_account','ss.bank_legal','u.id as uid','u.phone')
            ->paginate($limit);

        return s_msg('',$withdraw_list);

    }

    /**
     * @OA\Post(
     *     path="/withdrawXq",
     *     tags={"提现"},
     *     summary="详情",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"id"},
     *                 @OA\Property(property="id", type="number", description="id"),
     *                 @OA\Property(property="type", type="string", description="类型  fil"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function xq(Request $request)
    {

        if($request->has('id')){
            $id = $request->input('id');
            $type = $request->input('type');

            $xq = DB::table('withdraw as w')
                ->leftJoin('snapshot as ss','ss.order_id','=','w.id')
                ->where('w.id',$id)
                ->where('ss.type',$type)
                ->select('w.*','ss.wallet','ss.bank_name','ss.bank_account','ss.bank_legal')
                ->first();

            return s_msg('',$xq);

        }else{
            return e_msg(300019,'请传入id ');
        }

    }

    /**
     * @OA\Post(
     *     path="/admin/withdraw_check",
     *     tags={"提现"},
     *     summary="审核",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"id,state,reject_reason"},
     *                 @OA\Property(property="id", type="number", description="提现单子id id"),
     *                 @OA\Property(property="state", type="number", description="通过1，驳回2"),
     *                 @OA\Property(property="reject_reason", type="string", description="驳回理由"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function check(Request $request)
    {

        if($request->has('id')){
            $id = $request->input('id');
        }else{
            return e_msg(300019,'未传入id id');
        }

        $info = DB::table('withdraw as w')
            ->join('user as u','u.username','=','w.user_name')
            ->where('w.id', $id)
            ->select(
                'w.id',
                'w.state',
                'w.token',
                'w.amount',
                'u.username',
                'u.phone',
                'w.type'
            )
            ->first();
        if ($info === null) {
            return e_msg(300020,'提现订单信息不存在');
        }

        $info_state = $info->state;

        if ($info_state != 0) {

            return e_msg(300023,'该记录已审核');

        }

        $state = $request->input("state");

        if ($state != 1 && $state != 2) {

            return e_msg(300024,'审核提交状态有误state不是1或2');

        }
        $update_arr = [
            'state' => $state,
            'check_time' => date('Y-m-d H:i:s'),
        ];

        if($state == 1){
            DB::table('withdraw')->where('id',$id)->update($update_arr);

        }else{

            if (!$request->has('reject_reason') || !$request->input('reject_reason')) {

                return e_msg(300025,"请传入驳回理由 reject_reason");

            } else {
                $update_arr['note'] = $request->input('reject_reason');

            }

            $fil_insert_arr[] = [
                'out_account' => $info->username,
                'out_phone' =>  $info->phone,
                'shift_account' => '系统',
                'shift_phone' => '系统',
                'amount' => $info->amount,
                'type_note' => '提现驳回',
                'type' => 'reject',
                'coin_type' => $info->type,
            ];

            //提现表状态改变，用户添加eth,eth记录添加驳回
            DB::beginTransaction();

            $rel1 = DB::table('withdraw')->where('id',$id)->update($update_arr);
            $rel2 = DB::table('user')->where('username',$info->username)->increment($info->type,$info->amount);
            $rel3 = DB::table('record_fil')->insert($fil_insert_arr);
            if($rel1&&$rel2&&$rel3){
                DB::commit();
            }else{
                DB::rollBack();
                return e_msg(123456,'有问题');
            }

        }
        return s_msg('');


    }
}
